//
//  LCNetworkManager+Extensions.swift
//  SwiftWeiBo
//
//  Created by LiCheng on 2017/2/12.
//  Copyright © 2017年 LiCheng. All rights reserved.
//

import Foundation

// MARK: - 获取用户信息
extension LCNetworkManager {

    /// 加载当前用户信息 - 登录后立即执行
    func loadUserInfo(completion:@escaping (_ dict: [String: AnyObject]) -> ()) {

        guard let uid = userAccount.uid else {
            return
        }

        let urlStr = "https://api.weibo.com/2/users/show.json"
        let params = ["uid": uid]

        tokenRequest(URLString: urlStr, parameters: params as [String : AnyObject]?, completion: { (json, isSuccess) in

            completion((json as? [String: AnyObject]) ?? [:])
        })
    }
}


// MARK: - 微博相关请求
extension LCNetworkManager {



    /// 请求微博数据
    ///
    /// - Parameters:
    ///   - since_id:   返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0 - 下拉刷新
    ///   - max_id:     返回ID小于或等于max_id的微博，默认为0 - 上拉加载
    ///   - completion: 完成回调[list: 微博数组，isSuccess:是否成功]
    func loadStatusList(since_id: Int64 = 0, max_id:Int64 = 0, completion: @escaping (_ list: Any?, _ isSuccess: Bool)->()) {

        let url = "https://api.weibo.com/2/statuses/home_timeline.json"

        // swift int 可以转换成 anyobject 但是 int64不可以自动转换
        let params = ["since_id": "\(since_id)",
            "max_id": "\(max_id > 0 ? max_id - 1 : 0)"]

        LCNetworkManager.shared.tokenRequest(URLString: url, parameters: params as [String : AnyObject]?) { (json, isSuccess) in

            if isSuccess {
                let data = json as? [String: AnyObject]
                let result = data?["statuses"]

                completion(result,true)

            }else{
                completion(nil, false)
            }
        }
    }



    /// 返回微博的未读数
    ///
    /// - Parameter completion: 回调
    func loadUnreadCount(completion:@escaping (_ count: Int) -> ()) {

        guard let uid = userAccount.uid else {
            return
        }

        let urlStr = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]

        tokenRequest(URLString: urlStr, parameters: params as [String : AnyObject]?) { (json, isSuccess) in

            let dict = json as? [String: AnyObject]

            let count = dict?["status"] as? Int

            completion(count ?? 0)
        }
    }
}

// MARK: - OAuth 相关方法
extension LCNetworkManager {

    /// 获取 token
    ///
    /// - Parameters:
    ///   - code:  授权码
    ///   - completion: 完成回调
    func loadAccessToken(code: String, completion:@escaping (_ isSuccess: Bool) -> () ) {

        let urlStr = "https://api.weibo.com/oauth2/access_token"

        let params = ["client_id": WBAppKey,
                      "client_secret": WBAppSecret,
                      "grant_type": "authorization_code",
                      "code": code,
                      "redirect_uri": WBRedirectURI,]

        LCNetworkManager.shared.request(method: .POST, URLString: urlStr, parameters: params as [String : AnyObject]?) { (json, isSuccess) in

            // 如果请求失败，对之前保存的数据不会有任何影响
            // 1. 使用 yymodel 来设置字典
            //    - 空字典: [:] 空数组 []
            self.userAccount.yy_modelSet(with: (json as? [String: AnyObject]) ?? [:])


            // 2. 加载用户信息
            self.loadUserInfo(completion: { (dict) in

                // 1> 使用用户信息字典设置用户信息（昵称，头像地址）
                self.userAccount.yy_modelSet(with: dict)

                // 2> 保存模型
                self.userAccount.saveAccount()

                // 3> 加载完用户信息完成回调
                completion(isSuccess)
            })
        }
    }
}
